﻿#pragma warning disable 0649

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kinect;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace KinectApplication
{
    public static class MouseFaker
    {
        public const int MouseEventMove = 0x01;
        public const int MouseEventLeftDown = 0x02;
        public const int MouseEventLeftUp = 0x04;
        public const int MouseEventRightDown = 0x08;
        public const int MouseEventRightUp = 0x10;
        public const int MouseEventAbsolute = 0x8000;

        // Mouse status
        private static bool leftDown = false;
        private static bool rightDown = false;

        [DllImport("user32.dll", SetLastError = true)]
        private static extern uint SendInput(uint numInputs, Input[] inputs, int size);

        public static void MouseEvent(int positionX, int positionY, bool leftPressed, bool rightPressed)
        {
            Input[] i = new Input[2];

            i[0] = new Input();
            i[0].Type = 0;
            i[0].MouseInput.X = (positionX * 65535) / (int)System.Windows.SystemParameters.PrimaryScreenWidth;
            i[0].MouseInput.Y = (positionY * 65535) / (int)System.Windows.SystemParameters.PrimaryScreenHeight;
            i[0].MouseInput.Flags = MouseEventAbsolute | MouseEventMove;

            if (leftDown)
            {
                if (!leftPressed)
                {
                    i[1] = new Input();
                    i[1].Type = 0;
                    i[1].MouseInput.Flags = MouseEventLeftUp;
                    leftDown = false;
                }
            }
            else if (rightDown)
            {
                if (!rightPressed)
                {
                    i[1] = new Input();
                    i[1].Type = 0;
                    i[1].MouseInput.Flags = MouseEventRightUp;
                    rightDown = false;
                }
            }
            else
            {
                if (leftPressed)
                {
                    i[1] = new Input();
                    i[1].Type = 0;
                    i[1].MouseInput.Flags = MouseEventLeftDown;
                    leftDown = true;
                }
                else if (rightPressed)
                {
                    i[1] = new Input();
                    i[1].Type = 0;
                    i[1].MouseInput.Flags = MouseEventRightDown;
                    rightDown = true;
                }
            }

            uint result = SendInput(2, i, Marshal.SizeOf(i[0]));
            if (result == 0)
                throw new Win32Exception(Marshal.GetLastWin32Error());
        }
    }
}
